/**
*====================================================
* 文件名称: MyProtocolEncoder.java
* 修订记录：
* No    日期				作者(操作:具体内容)
* 1.    2010-1-22			李自立(创建:创建文件)
*====================================================
* 类描述：(说明未实现或其它不应生成javadoc的内容)
* 
*/
package com.sunsharing.transport.mina;

import java.io.NotSerializableException;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;


import com.sunsharing.common.Context;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

/**
 *<pre><b><font color="blue">MyProtocolEncoder</font></b></pre>
 *
 *<pre><b>&nbsp;--描述说明--</b></pre>
 * <pre></pre>
 * <pre>
 * <b>--样例--</b>
 *   MyProtocolEncoder obj = new MyProtocolEncoder();
 *   obj.method();
 * </pre>
 * JDK版本：JDK1.5
 * @author  <b>李自立</b> 
 */
public class MyProtocolEncoder extends ProtocolEncoderAdapter {
	
	private final Charset charset;

	public MyProtocolEncoder(Charset charset) {
		this.charset = charset;
	}

	/* (non-Javadoc)
	 * @see org.apache.mina.filter.codec.ProtocolEncoder#encode(org.apache.mina.core.session.IoSession, java.lang.Object, org.apache.mina.filter.codec.ProtocolEncoderOutput)
	 */
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {

//		if (!(message instanceof Serializable)) {
//
//		            throw new NotSerializableException();
//		}

		IoBuffer buf = IoBuffer.allocate(1024);
		buf.setAutoExpand(true);
        byte[] array = ((Context)message).serialization();
		buf.put(intToBytes(array.length));
        buf.put(array);
		buf.flip();
		out.write(buf);

	}
    public static byte[] intToBytes(int n) {
        byte[] b = new byte[4];
        b[3] = (byte) (n & 0xff);
        b[2] = (byte) (n >> 8 & 0xff);
        b[1] = (byte) (n >> 16 & 0xff);
        b[0] = (byte) (n >> 24 & 0xff);
        return b;
    }

}
